package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mappers.UserInfoMapper;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.service.UserInfoApi;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author げっしょく
 * @date 2021/10/23
 */

@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void updateById(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfo getUserById(Long userID) {
        UserInfo userInfo = userInfoMapper.selectById(userID);
        return userInfo;
    }

    @Override
    public Map<Long, UserInfo> getByUserIds(List<Long> userIds, UserInfo userInfo) {
        QueryWrapper qw = new QueryWrapper();
        qw.in("id",userIds);
        if (userInfo != null) {
            Integer age = userInfo.getAge();
            String gender = userInfo.getGender();
            String nickname = userInfo.getNickname();
            qw.lt(age != null,"age", age);
            qw.eq(StringUtils.isNotEmpty(gender),"gender", gender);
            qw.like(StringUtils.isNotEmpty(nickname), "nickname", nickname);
        }
        List<UserInfo> list = userInfoMapper.selectList(qw);
        Map<Long, UserInfo> map = list.stream().collect(Collectors.toMap(u -> u.getId(), u -> u));
        return map;
    }

    @Override
    public Map getByIds(List<Long> users) {
        List<UserInfo> userInfos = userInfoMapper.selectBatchIds(users);
        Map<Long, UserInfo> collect = userInfos.stream().collect(Collectors.toMap(u -> u.getId(), Function.identity()));
        return collect;
    }

    @Override
    public PageResult getUserPageUser(Integer page, Integer pagesize) {
        Integer integer = userInfoMapper.selectCount(null);
        Page<UserInfo> page1 = userInfoMapper.selectPage(new Page<>(page, pagesize), null);
        List<UserInfo> records = page1.getRecords();
        PageResult pageResult = new PageResult(page, pagesize, Long.valueOf(integer), records);
        return pageResult;
    }


}
